package com.zyx.xunyilu.config;

import com.zyx.xunyilu.utils.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @AUTHOR soft
 * @DATE 2018/12/20 22:55
 * @DESCRIBE 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(AuthenticationException.class)
    public RestResponse handleAuthenticationExceptionException(Exception e) {
        log.error("{}", e.getMessage());
        return RestResponse.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(UnknownAccountException.class)
    public RestResponse handleUnknownAccountExceptionException(Exception e) {
        log.error("{}", e.getMessage());
        return RestResponse.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(AuthorizationException.class)
    public RestResponse handleAuthorizationException(Exception e) {
        log.error("没有权限的操作");
        return RestResponse.fail("没有权限");
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public RestResponse handleBindException(BindException e) {
        String defaultMessage = e.getFieldErrors().get(0).getDefaultMessage();
        log.error("{}", defaultMessage);
        return RestResponse.fail(defaultMessage);
    }

    @ExceptionHandler
    @ResponseBody
    public RestResponse handler(Exception e) {
        e.printStackTrace();
        log.error("{}", e.getMessage());
        return RestResponse.fail(e.getMessage());
    }
}
